package com.xy.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xy.entity.SysUser;
import com.xy.mapper.SysPermissionMapper;
import com.xy.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class MyService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //mybatisPlus 根据 账号 查询
        QueryWrapper<SysUser> qw = new QueryWrapper<>();
        qw.eq("username",username);
        SysUser sysUser = sysUserMapper.selectOne(qw);
        //如果查询结果不为空 查询角色拥有的所有权限,否则返回空
        if(Objects.nonNull(sysUser)){
            //将根据 用户id 联表查询 权限Collection集合 转换成 SimpleGrantedAuthority集合
            List<SimpleGrantedAuthority> list = sysPermissionMapper.selectPermissionByUserId(sysUser.getUserid())
                    .stream().map(data -> new SimpleGrantedAuthority(data.getPercode())).collect(Collectors.toList());
            return new User(username,sysUser.getUserpwd(),list);
        }
        return null;
    }
}